package com.nciae.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nciae.po.Hoursemaster;
import com.nciae.dao.HoursemasterMapper;
import com.nciae.po.Teacher;
import com.nciae.po.User;
import com.nciae.service.IHoursemasterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nciae.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Guoliyu
 * @since 2022-03-31
 */
@Service
public class HoursemasterServiceImpl extends ServiceImpl<HoursemasterMapper, Hoursemaster> implements IHoursemasterService {

    @Autowired
    private IUserService userService;


    @Override
    public List<Hoursemaster> findAll(String username) {
        List<Hoursemaster> hoursemasters = new ArrayList<>();
        List<User> users = userService.findUserByUsername(username);
        for(User user:users) {
            Hoursemaster hoursemaster = baseMapper.selectById(user.getId());
            if (!Objects.isNull(hoursemaster)) {
                hoursemaster.setUser(user);
                hoursemasters.add(hoursemaster);
            }
        }
        return hoursemasters;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Hoursemaster hoursemaster) {
        String userJson = hoursemaster.getUserJson();
        ParserConfig.getGlobalInstance().addAccept("com.nciae.po.User");
        User user = (User) JSONObject.parse(userJson);
        if (!Objects.isNull(user)) {
            userService.add(user);
        }
        hoursemaster.setId(user.getId());
        baseMapper.insert(hoursemaster);
    }

    @Override
    @Transactional
    public void update(Hoursemaster hoursemaster) {
        String userJson = hoursemaster.getUserJson();
        User user = (User) JSONObject.parse(userJson);
        user.setId(hoursemaster.getId());
        if (!Objects.isNull(user)) {
            userService.update(user);
        }
        baseMapper.updateById(hoursemaster);
    }

    @Override
    public void delete(Long id) {
        userService.delete(id);
        baseMapper.deleteById(id);
    }

    @Override
    public Hoursemaster findHoursemasterById(Long id) {
       return baseMapper.selectById(id);
    }

    @Override
    public void addList(List<Hoursemaster> hoursemasters) {
        if (!Objects.isNull(hoursemasters)) {
            for(Hoursemaster hoursemaster : hoursemasters) {
                add(hoursemaster);
            }
        }
    }
}
